<template>
  <update class="update-window" ref="updateWindow" @close="onClose" v-if="!networkNone"></update>
  <tip ref="tipsshow"></tip>
  <poster ref="postershow" @close="onClose"></poster>
  <view class="viewport" v-show="!networkNone">
    <view class="home_topimg">
      <image src="../../static/images/home_topimg11.png" mode="aspectFit" />
    </view>
    <view class="store">
      <view class="store-choose">
        <view class="c1 fs36 fw500 store_name" @click="toStorePage(site.id)">{{ site.name || '-' }}</view>
        <image class="to-more" src="../../static/icons/icon-toright.png" mode="widthFix" />
      </view>
      <view class="tips-v" @click="toNoticeList">
        <view class="tips">
          <view class="tips_icon">
            <image :class="['ttt', lingShow ? 'ttt_animation' : '']" src="../../static/tabs/t1.png" mode="widthFix">
            </image>
            <image :class="['fff', lingShow ? 'fff_animation' : '']" src="../../static/tabs/t2.png" mode="widthFix">
            </image>
          </view>
          <view v-if="noticeNumber > 0">
            <text class="fs28 c1 fw400">有</text>
            <text class="fs28 c5 fw700">{{ noticeNumber < 999 ? noticeNumber : '999+' }}</text>
            <text class="fs28 c1 fw400">条新消息</text>
          </view>
          <text class="fs28 c1 fw400" style="margin-left: 0" v-if="noticeNumber == 0">消息中心</text>
        </view>
      </view>
    </view>

    <!-- 滚动容器 -->
    <scroll-view enable-back-to-top refresher-enabled @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered" class="scroll-view" scroll-y refresher-background="#f7f8fa">
      <!-- 短租待办事项 -->
      <Needtobe ref="needtobePage" />
      <Tool ref="toolPage" />
      <DataBoard ref="dataBoard" v-if="userStore().v_auth('svmapp:1:databoard')" />
      <view style="height: 20rpx; width: 100%"></view>
    </scroll-view>
  </view>
  <view class="none-network" v-show="networkNone">
    <ve-empty type="network" text="暂无网络,请重新加载"></ve-empty>
    <ve-button type="plain" style="margin-top: 80rpx" @click="onRefresherrefresh">重新加载</ve-button>
  </view>
</template>

<script setup lang="ts">
  // 选择门店请求对应数据,目前接口未出
  // onRefresherrefresh为需要刷新的内容或请求,填入方法即可
  import dayjs from 'dayjs'
  import { onReady, onShow, onLoad, onUnload } from '@dcloudio/uni-app'
  import { nextTick, ref } from 'vue'
  import Needtobe from './components/needtobe.vue'
  import Tool from './components/tool.vue'
  import update from '@/components/update-APP/index.vue'
  import DataBoard from './components/databoard.vue'
  import tip from './components/tips.vue'
  import poster from './components/posters.vue'
  import { changeSite } from '@/api/home/index'
  import { userStore } from '@/stores'
  import { appversion } from '@/api/common/login'
  import { noticeList, noticeUnnums } from '@/api/home/index'
  const userInfoStore = userStore()
  const { statusBarHeight = 0 } = uni.getSystemInfoSync()
  const networkNone = ref(false)
  const needtobePage = ref(null) // 获取首页数据统计
  const toolPage = ref(null) // 按钮
  const dataBoard = ref(null)
  const noticeNumber = ref(0) // 未读消息数
  const updateWindow = ref(null)
  const tipsshow = ref(null)
  const postershow = ref<any>(null)
  const lingShow = ref(false) //铃铛动效
  const site = ref({
    name: '',
    code: '',
    id: '',
    isUserInterestOrder: '-1',
  })
  const isTriggered = ref(false) // 当前下拉刷新状态
  const updateWindowShow = ref(false)


  const is_inited = ref(false)
  const getHomeNumData = (siteId, siteName) => {
    // console.log('有网络时,请求主页数据2')
    // console.log(needtobePage.value)
    if (needtobePage.value) {
      needtobePage.value.getNums(siteId, siteName)
    }
    if (toolPage.value) {
      toolPage.value.getTool()
    }
    if (dataBoard.value) {
      dataBoard.value.getData(siteId, siteName)
      dataBoard.value.getchartData(siteId, siteName)
    }
  }
  const toStorePage = (id) => {
    uni.navigateTo({
      url: '/pages/index/store?id=' + (id ? id : ''),
    })
  }
  // 选完门店后
  uni.$on('chooseStore', function (data) {
    site.value.name = data.name
    site.value.code = data.code
    site.value.id = data.id
    site.value.isUserInterestOrder = data.isUserInterestOrder
    changeSite() //门店切换
    getHomeNumData(site.value.id, site.value.name)
  })
  const getNoticeNum = () => {
    // 消息数量
    noticeUnnums().then((res) => {
      // console.log(res)
      noticeNumber.value = Number(res.result.type1 ? res.result.type1 : 0) + Number(res.result.type2 ? res.result.type2 : 0)
      // console.log('消息数量：', noticeNumber.value)
      if (noticeNumber.value > 0) {
        lingShow.value = true
        setTimeout(() => {
          lingShow.value = false
        }, 1200)
      }
    })
  }
  const onClose = (e) => {
    // 海报关闭、关闭更新、更新弹窗判定不显示时,执行消息相关方法
    // console.log(e)
    noticeFns()
  }
  const toNoticeList = () => {
    uni.navigateTo({
      url: '/pages/info/list',
    })
  }
  // 获取首页系统消息
  const getIndexNotice = () => {
    // console.log('获取首页系统消息')
    // 消息列表
    // 第一条系统消息未读则弹窗
    noticeList({
      source: 1,
      needAppPush: 1,
      noticeType: 2,
      pageNumber: 1,
      pageSize: 10,
    }).then((res) => {
      // console.log(res)
      if (res.result.data && res.result.data.length) {
        if (res.result.data[0].userStatus != 1 && res.result.data[0].appPositionList.includes(2)) {
          // 发现第一条是未读，动效且弹窗
          var noticeId = res.result.data[0].id
          tipsshow.value.open(noticeId)
          lingShow.value = true
          setTimeout(() => {
            lingShow.value = false
          }, 1200)
        } else {
          // noticeId去列表里第一条未读
          var list = res.result.data
          list.forEach((i) => {
            if (i.userStatus != 1 && i.appPositionList.includes(2)) {
              var noticeId = i.id
              var noticeTime = uni.getStorageSync('noticeTime')
              console.log('noticeTime', noticeTime)
              // 无缓存弹窗时间 或 今日不等于弹窗记录时间,则弹窗
              if (!noticeTime) {
                uni.setStorageSync('noticeTime', dayjs().format('YYYY-MM-DD'))
                tipsshow.value.open(noticeId)
              } else if (noticeTime && noticeTime != dayjs().format('YYYY-MM-DD')) {
                uni.setStorageSync('noticeTime', dayjs().format('YYYY-MM-DD'))
                tipsshow.value.open(noticeId)
              }
              return false
            }
          })

        }
      }
      getNoticeNum()
    })
  }
  onUnload(() => {
    uni.$off('chooseStore')
    uni.offPushMessage((res) => {
      console.log(res)
    })
  })
  // 页面加载
  onReady(async () => {
    var homeSite = uni.getStorageSync('homeSite')
    getHomeNumData(homeSite.id, homeSite.name)
  })
  const tipsGet = () => {
    // 网络 => 更新 => 海报 => 消息
    var homeSite = uni.getStorageSync('homeSite')
    site.value = homeSite
    if (homeSite) {
      // console.log('缓存', homeSite)
      getHomeNumData(homeSite.id, homeSite.name)
    } else {
      // console.log('无缓存', homeSite)
      site.value = {
        name: '全部门店',
      }
      getHomeNumData()
    }
    if (userInfoStore.profile) {
      // 请求版本
      // #ifdef APP-PLUS
      appversion({}).then((res) => {
        var serverVersion = res.result.version.split('.').join('') //服务器版本
        plus.runtime.getProperty(plus.runtime.appid, function (info) {
          var systemVersion = info.version.split('.').join('') //本地版本
          console.log('👆服务器版本:' + serverVersion + '      ' + '👇本地版本:' + systemVersion)
          if (Number(serverVersion) > Number(systemVersion)) {
            // 弹出更新弹窗
            updateWindowShow.value = true
            setTimeout(() => {
              updateWindow.value.show(res)
            }, 0)
          } else {
            // 无需更新
            updateWindowShow.value = false
            noticeFns()

            // 欢度新年海报
            // 6.2.5版本后不提示新年了
            // postershow.value.open()
          }
        })
      })
      // #endif
      // #ifdef H5
      // 欢度新年海报
      // nextTick(() => {
      //   postershow.value.open()
      // })
      // #endif
    }
  }
  onShow(() => {
    uni.getNetworkType({
      success: function (res) {
        if (res.networkType == 'none') {
          networkNone.value = true // 无网络
        } else {
          networkNone.value = false // 有网络
          tipsGet()
        }
      },
    })
  })
  // 监听网络连接
  uni.onNetworkStatusChange((res) => {
    if (!res.isConnected) {
      networkNone.value = true
    }
  })
  // 获取消息数量,获取消息,监听
  const noticeFns = () => {
    getNoticeNum()
    getIndexNotice()
    listenTranMsg()
  }
  onLoad(() => {
    console.log('🐳 ~ APP-IndexPage ~ onLoad:')
    // 获取用户配置
    userInfoStore.setIndexInfo()
  })
  // 监听透传消息
  const listenTranMsg = () => {
    uni.getProvider({
      service: 'push',
      success: function (res) {
        // console.log(res.provider)
        if (~res.provider.indexOf('unipush')) {
          uni.onPushMessage((res) => {
            // console.log(res)
            var payload = res.data.payload
            // console.log('payload', payload)
            if (payload) {
              // 动效+获取新消息判断是否弹窗
              lingShow.value = true
              setTimeout(() => {
                lingShow.value = false
              }, 1200)
              // 更新消息数量
              getNoticeNum()
              getIndexNotice()
            }
          })
        }
      }
    })
  }
  const onRefresherrefresh = () => {
    uni.getNetworkType({
      success: function (res) {
        if (res.networkType == 'none') {
          networkNone.value = true // 无网络
        } else {
          networkNone.value = false // 有网络
          if (!userInfoStore.profile) {
            uni.reLaunch({ url: '/pages/login/login' })
          } else {
            isTriggered.value = true
            // console.log('有网络时,请求主页数据1')
            // await Promise.all([getHomeNumData()])
            getHomeNumData(site.value.id, site.value.name)
            //关掉圈圈，需要先执行完刷新操作
            uni.removeStorageSync('noticeTime')
            tipsGet()
            setTimeout(() => {
              isTriggered.value = false
            }, 1000)
          }
        }
      },
    })
  }
</script>

<style lang="scss" scoped>
  page {
    height: 100%;
    overflow: hidden;
  }

  .update-window {
    z-index: 1001;
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.6);
  }

  .viewport {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    .home_topimg {
      background: #ffd3a3;
      width: 100%;
      position: absolute;
      height: 172rpx;
      top: 0;
      left: 0;
      text-align: right;
      overflow: hidden;

      image {
        width: 750rpx;
        height: 172rpx;
      }
    }
  }

  .store {
    height: 172rpx;
    width: 100%;
    position: sticky;
    top: 0;
    left: 0;

    .store-choose {
      position: absolute;
      left: 24rpx;
      bottom: 16rpx;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .store_name {
        max-width: 340rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .to-more {
        width: 32rpx;
        height: 32rpx;
        margin-left: 8rpx;
      }
    }

    .tips-v {
      width: 50%;
    }

    .tips {
      // width: 50%;
      padding: 4rpx 16rpx;
      border-radius: 100rpx;
      background-color: rgba(255, 255, 255, 0.6);
      display: inline-block;
      position: absolute;
      bottom: 14rpx;
      right: 24rpx;

      .tips_icon {}

      display: flex;
      justify-content: center;
      align-items: center;

      text:nth-child(1) {}

      text:nth-child(2) {
        margin: 0 12rpx;
      }

      text:nth-child(3) {}
    }

  }

  .scroll-view {
    flex: 1;
    overflow: hidden;
    background: #f7f8fa;
  }

  .none-network {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    flex-direction: column;
  }

  .tips_icon {
    width: 40rpx;
    height: 40rpx;
    position: relative;

    .ttt {
      position: absolute;
      top: 6rpx;
      right: 2rpx;
      width: 26rpx;
      height: 26rpx;
      transform: rotate(18deg);
      transform-origin: 50% 0%;
    }

    .ttt_animation {
      animation: ooo 1.2s 0s linear 1;
    }

    .fff {
      position: absolute;
      top: 26.5rpx;
      right: 16.5rpx;
      width: 12rpx;
      height: 12rpx;
      transform: rotate(18deg);
    }

    .fff_animation {
      animation: sss 1.2s 0s linear 1;
    }
  }

  @keyframes ooo {
    0% {
      transform: rotate(18deg);
      transform-origin: 50% 0%;
    }

    25% {
      transform: rotate(38deg);
      transform-origin: 50% 0%;
    }

    45% {
      transform: rotate(18deg);
      transform-origin: 50% 0%;
    }

    55% {
      transform: rotate(18deg);
      transform-origin: 50% 0%;
    }

    75% {
      transform: rotate(38deg);
      transform-origin: 50% 0%;
    }

    100% {
      transform: rotate(18deg);
      transform-origin: 50% 0%;
    }
  }

  @keyframes sss {
    0% {
      transform: rotate(18deg);
      top: 29rpx;
      right: 12rpx;
    }

    25% {
      transform: rotate(38deg);
      top: 21rpx;
      right: 28rpx;
    }

    45% {
      transform: rotate(18deg);
      top: 29rpx;
      right: 12rpx;
    }

    55% {
      transform: rotate(18deg);
      top: 29rpx;
      right: 12rpx;
    }

    75% {
      transform: rotate(38deg);
      top: 21rpx;
      right: 28rpx;
    }

    100% {
      transform: rotate(18deg);
      top: 29rpx;
      right: 12rpx;
    }
  }
</style>
[x: string]: any;

[x: string]: any;
